<template>
	<el-dialog title="创建样式" width="500" v-model="visible" @close="closeDialog" draggable>
		<el-form ref="styleDialogFormRef" label-position="left" :model="dataForm" :rules="dataRules" label-width="80px" v-loading="loading">
			<el-row :gutter="20">
				<el-col :span="24" class="mb20">
					<el-form-item label="样式ID" prop="styleName">
						<el-input v-model="dataForm.styleName" clearable @input="handleInput" placeholder="只能输入英文和下划线"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="样式名称" prop="styleNameCh">
						<el-input v-model="dataForm.styleNameCh" clearable placeholder="请输入样式名称"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="15" class="mb20">
					<el-form-item label="所属项目" prop="projectName">
						<el-select v-model="dataForm.projectName" :suffix-icon="IconDropDown" placeholder="选择所属项目" clearable>
							<el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="9" class="mb20">
					<el-form-item label="是否启用" prop="onEnable" class="float-right">
						<el-switch v-model="dataForm.onEnable" active-value="1" inactive-value="0" />
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="样式说明" prop="styleBack">
						<el-input v-model="dataForm.styleBack" clearable placeholder="请输入样式说明"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="类型" prop="styleType">
						<el-radio-group v-model="dataForm.styleType">
							<el-radio-button label="1">点</el-radio-button>
							<el-radio-button label="2">线</el-radio-button>
							<el-radio-button label="3">面</el-radio-button>
							<el-radio-button label="4">栅格图层</el-radio-button>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="格式" prop="styleFormat">
						<el-radio-group v-model="dataForm.styleFormat" @change="formatChange">
							<el-radio-button label="sld">SLD</el-radio-button>
							<el-radio-button label="zip">ZIP</el-radio-button>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item prop="file">
						<div class="flex">
							<el-upload v-model:file-list="fileList" class="upload-demo" :auto-upload="false" :limit="1" :on-change="beforeUpload">
								<el-button icon="CirclePlus" type="primary">添加文件</el-button>
							</el-upload>
							<span style="color: #b9c2cd" class="text-sm ml-2">{{ `导入${uploadTip}配置文件` }}</span>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button class="w-24" type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.createBtn') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="styleDialog">
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { useUserInfo } from '/@/stores/userInfo';
import { creatStyle } from '/@/api/resource/style';
import DropDown from '/@/assets/icons/drop-down.svg';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();
// 引入组件
// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const styleDialogFormRef = ref();
const acceptFile = ref(['sld']);
const fileList = ref([]);
const projectOptions = computed(() => {
	return useUserInfo().userInfos.projectList;
});
// 定义需要的数据
const dataForm = reactive({
	styleNameCh: '',
	layerName: '',
	styleName: '',
	projectName: '',
	onEnable: '1',
	styleBack: '',
	styleType: '1',
	styleFormat: 'sld',
	file: null,
});
const fileType = ref('');
const headers = computed(() => {
	return {
		Accept: 'application/octet-stream',
	};
});
const uploadTip = ref('SLD');
const IconDropDown = {
	render: () => {
		return h('img', { src: DropDown });
	},
};

// 表单校验规则
const dataRules = reactive({
	styleNameCh: [{ required: true, message: '样式名称不能为空', trigger: 'blur' }],
	styleName: [{ required: true, message: '样式ID不能为空', trigger: 'blur' }],
	// projectName: [{ required: true, message: '所属项目不能为空', trigger: 'blur' }],
	styleBack: [{ required: true, message: '样式说明不能为空', trigger: 'blur' }],
});

//格式选择修改上传提示
const formatChange = (value: any) => {
	uploadTip.value = value;
	acceptFile.value = [value];
	dataForm.styleFormat = value;
};

// 打开弹窗
const openDialog = (type: string, row?: any) => {
	dataForm.layerName = '';
	visible.value = true;

	nextTick(() => {
		styleDialogFormRef.value?.resetFields();

		if (row?.id && type === 'edit') {
			dataForm.layerName = row.layerName;
		}
	});
};
const closeDialog = () => {
	visible.value = false;
	fileList.value = [];
};

//上传成功
const beforeUpload = (file: any) => {
	if (acceptFile.value.length > 0) {
		const fileName = file.name.split('.');
		const fileExt = fileName[fileName.length - 1];
		fileType.value = fileExt;
		const isTypeOk = acceptFile.value.indexOf(fileExt) >= 0;
		if (!isTypeOk) {
			useMessage().error(`文件格式不正确, 请上传${acceptFile.value.join('/')}格式文件!`);
			dataForm.file = null;
			fileList.value = [];
			return false;
		}
		dataForm.file = file.raw;
	}
};

//限制名称只能是英文
const handleInput = (e) => {
	const regex = /^[a-zA-Z_]+$/;
	if (!regex.test(dataForm.styleName)) {
		// 输入不符合要求，进行处理
		// 或者可以禁止用户输入非英文字符
		dataForm.styleName = dataForm.styleName.replace(/[^a-zA-Z_]/g, '');
	}
};

function selectSinglePartFile(file: any) {}
// 保存数据
const onSubmit = async () => {
	const valid = await styleDialogFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		// dataForm.menuId ? await putObj(dataForm) : await addObj(dataForm);
		var fileParam = new FormData();
		fileParam.append('file', dataForm.file);
		fileParam.append('styleNameCh', dataForm.styleNameCh);
		fileParam.append('styleName', dataForm.styleName);
		console.log(typeof dataForm.projectName);
		fileParam.append('projectName', dataForm.projectName);
		fileParam.append('onEnable', dataForm.onEnable);
		fileParam.append('styleBack', dataForm.styleBack);
		fileParam.append('styleType', dataForm.styleType);
		fileParam.append('styleFormat', dataForm.styleFormat);
		let res = await creatStyle(fileParam);
		if(res.code==0){
			useMessage().success(t(dataForm.layerName ? 'common.editSuccessText' : 'common.publishSuccessText'));
		}else if(res.code==1){
		return
		}
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
:deep(.el-radio-button) {
	margin-right: 10px;
	--el-border-radius-base: 0px;
}

:deep(.el-radio-button__inner) {
	color: #000;
	background-color: #eaf1ff;
	width: 80px !important;
}
.dialog-footer {
	display: flex;
	justify-content: center;
}

.blue-card {
	margin: 5px;
	padding: 10px;
	border-radius: 8px;
	background: #edf0f7;
}
</style>
